<?php
class PeoplePracticesController extends AppController {

	var $name = 'PeoplePractices';
	var $uses = array('PeoplePractice','Person','Practice','Combo','CombosPractice');

    function beforeFilter () {
        parent::beforeFilter();

		// Aplico el Layout segun la Vista o si es AJAX
		if ($this->RequestHandler->isAjax()) {
			$this->layout = 'ajax';
		}else{
			// Cambio la Vista por la del Rol
			$this->layout = strtolower($this->Session->read('VistaActual'));
		}
    }
    
	function index($id_paciente = null, $archivados = null) {
		$this->PeoplePractice->recursive = 0;

		if(!$archivados){
			$peoplePractices = $this->PeoplePractice->find('all', array(
							'conditions' => array(
												'PeoplePractice.client_id' => $this->Session->read('ClientesUsuarioLogueado.id'),
												'PeoplePractice.person_id' => $id_paciente,
												'NOT' => array ('PeoplePractice.staterecord_id' => array('2','3'))
											),
							'order' => array('PeoplePractice.fecha DESC', 'Practice.name'),
							'fields' => array('PeoplePractice.id', 'PeoplePractice.fecha', 'PeoplePractice.person_id', 'Practice.name')
			) );
		}else{ // Para mostrar tambien los registros ARCHIVADOS
			$peoplePractices = $this->PeoplePractice->find('all', array(
							'conditions' => array(
												'PeoplePractice.client_id' => $this->Session->read('ClientesUsuarioLogueado.id'),
												'PeoplePractice.person_id' => $id_paciente,
												'NOT' => array ('PeoplePractice.staterecord_id' => array('2'))
											),
							'order' => array('PeoplePractice.fecha DESC', 'Practice.name'),
							'fields' => array('PeoplePractice.id', 'PeoplePractice.fecha', 'PeoplePractice.person_id', 'Practice.name')
			) );
		}
		$this->set('archivados', $archivados);

		$this->set('peoplePractices', $peoplePractices);
		$this->set('id_paciente', $id_paciente);
		$this->layout = 'ajax';
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid people practice', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('peoplePractice', $this->PeoplePractice->read(null, $id));
	}

	function add($id_paciente = null) {
		if (!empty($this->data)) {


			// Si no se selecciono ninguna Practica
			if(empty($this->data['PeoplePractice']['arregloPracticasSeleccionadas'])){
				$this->Session->setFlash(__('Debe seleccionar al menos una Práctica', true));
				$this->redirect('/people/view/'.$this->data['PeoplePractice']['person_id'].'/9');
				exit;
			}

			// Cargo todas las practicas asociadas
			foreach($this->data['PeoplePractice']['arregloPracticasSeleccionadas'] AS $id_practica_seleccionada){

				$this->PeoplePractice->create();

				// Seteo datos que no vienen del Formulario
				$this->PeoplePractice->set(array(
					'client_id' => $this->Session->read('ClientesUsuarioLogueado.id'),
					'user_id' => $this->Auth->user('id'),
					'practice_id' => $id_practica_seleccionada,
					'person_id' => $this->data['PeoplePractice']['person_id'],
					'fecha' => $this->data['PeoplePractice']['fecha'],
				));

				// Grabo cada Practica
				$this->PeoplePractice->save();
			}

			// Cargo todas las practicas asociadas a los COMBOS
			if(!empty($this->data['PeoplePractice']['arregloCombosSeleccionados'])){
				foreach($this->data['PeoplePractice']['arregloCombosSeleccionados'] AS $id_practica_combo_seleccionada){


					$arreglo_practica_combo_seleccionada = explode("|", $id_practica_combo_seleccionada); 

					foreach($arreglo_practica_combo_seleccionada AS $id_practica_combo){

						// Si el ID no esta vacio
						if(!empty($id_practica_combo)){
							// Creo un Registro
							$this->PeoplePractice->create();

							// Seteo datos que no vienen del Formulario
							$this->PeoplePractice->set(array(
								'client_id' => $this->Session->read('ClientesUsuarioLogueado.id'),
								'user_id' => $this->Auth->user('id'),
								'practice_id' => $id_practica_combo,
								'person_id' => $this->data['PeoplePractice']['person_id'],
								'fecha' => $this->data['PeoplePractice']['fecha'],
							));

							// Grabo cada Practica
							$this->PeoplePractice->save();
						}
					}
				}
			}

			$this->Session->setFlash(__('La Práctica ha sido asociada', true));
			$this->redirect('/people/view/'.$this->data['PeoplePractice']['person_id'].'/9');
			exit;
		}

		if (!$id_paciente) {
			exit;
		}

		$people = $this->Person->find('list', array(
						'conditions' => array('Person.id' => $id_paciente),
						'fields' => array('Person.id', 'Person.full_name')
		) );


		$combos = $this->Combo->find('all', array(
						'conditions' => array(
											'Combo.client_id' => $this->Session->read('ClientesUsuarioLogueado.id'),
											'Combo.user_id' => $this->Session->read('ProfesionalSeleccionado'),
										),
						'fields' => array('Combo.id', 'Combo.name')
		) );

//print_r($combos);

		$this->set('combos', $combos);
		$this->set('id_paciente', $id_paciente);
		$this->set(compact('people'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid people practice', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->PeoplePractice->save($this->data)) {
				$this->Session->setFlash(__('The people practice has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The people practice could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->PeoplePractice->read(null, $id);
		}
		$people = $this->PeoplePractice->Person->find('list');
		$practices = $this->PeoplePractice->Practice->find('list');
		$this->set(compact('people', 'practices'));
	}

	function archivar($id = null, $id_paciente = null, $estado = null) {
		if (!$id) {
			$this->Session->setFlash(__('Practica no valida', true));
			$this->redirect('/dashboards');
		}

		if (!$id_paciente) {
			$this->Session->setFlash(__('Paciente no valido', true));
			$this->redirect('/dashboards');
		}

		if (!$estado) {
			$this->Session->setFlash(__('Estado no valido', true));
			$this->redirect('/dashboards');
		}

		$this->PeoplePractice->id = $id;
		$this->PeoplePractice->set(array(
			'staterecord_id' =>  $estado,
			'user_id' => $this->Auth->user('id'),
		));


		if ($this->PeoplePractice->save()) {
			$this->Session->setFlash(__('La Practica fue procesada.', true));
			$this->redirect('/people/view/'.$id_paciente.'/9');
		}
		$this->Session->setFlash(__('La Practica no pudo ser procesada', true));
		$this->redirect('/people/view/'.$id_paciente.'/9');
	}

	function existePractica($id_paciente = null, $id_practica = null){

		if (!$id_paciente) {
			return 1;
		}

		if (!$id_practica) {
			return 1;
		}


		$practicaspaciente = $this->PeoplePractice->find('all', array(
						'conditions' => array(
											'PeoplePractice.client_id' => $this->Session->read('ClientesUsuarioLogueado.id'),
											'PeoplePractice.person_id' => $id_paciente,
											'PeoplePractice.practice_id' => $id_practica,
										),
						'fields' => array('Practice.id', 'Practice.name')
		) );


		// Si el Problema es Nuevo
		if(empty($practicaspaciente)){
			return 0;
		}else{
			return 1;
		}
	}

}
?>